/*
 * Copyright © 2020-present LiuDanYang. All rights Reserved.
 */

import { decrypt, encrypt } from "./encrypt";
// 项目名 + 项目版本 + name
const STORAGE_NAME = "INIT_1.0.0_";

/**
 * 加密存储数据
 * @param name
 * @param data
 */
export function setStorage(name, data) {
  const key = STORAGE_NAME + name;
  const encrypted = encrypt(JSON.stringify(data));
  uni.setStorageSync(key, encrypted);
}

/**
 * 解密获取数据
 * @param name
 * @returns {null|any}
 */
export function getStorage(name) {
  const key = STORAGE_NAME + name;
  const data = uni.getStorageSync(key);
  if (data) {
    try {
      return JSON.parse(decrypt(data));
    } catch (error) {
      return null;
    }
  }
  return null;
}

/**
 * 删除数据
 * @param name
 */
export function removeStorage(name) {
  const key = STORAGE_NAME + name;
  uni.removeStorageSync(key);
}

// token
const t = "_T";

export function getToken() {
  return getStorage(t);
}

export function setToken(data) {
  return setStorage(t, data);
}

export function removeToken() {
  return removeStorage(t);
}

// 微信openid
const OpenKey = "_W";

export function getWeChatAuth() {
  return getStorage(OpenKey);
}

export function setWeChatAuth(data) {
  return setStorage(OpenKey, data);
}

export function removeWeChatAuth() {
  return removeStorage(OpenKey);
}

const user = "_U";

// 获取用户信息
export function getLocalUserInfo() {
  return getStorage(user);
}

// 设置用户信息
export function setLocalUserInfo(data) {
  return setStorage(user, data);
}

// 移除用户信息
export function removeLocalUserInfo() {
  return removeStorage(user);
}
